/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.ui;

import com.bytedance.scene.SceneContainerLifecycleCallback;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;

/**
 * @hide
 */
public class LifeCycleCompatFragment extends Fraction {
    public static LifeCycleCompatFragment newInstance(boolean supportRestore) {
        LifeCycleCompatFragment fragment = new LifeCycleCompatFragment();
        return fragment;
    }

    private SceneContainerLifecycleCallback mSceneContainerLifecycleCallback = null;

    public void setSceneContainerLifecycleCallback(SceneContainerLifecycleCallback callback) {
        this.mSceneContainerLifecycleCallback = callback;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        if (this.mSceneContainerLifecycleCallback != null) {
            this.mSceneContainerLifecycleCallback.onStart(getFractionAbility(), intent);
        } else {
            removeSelfWhenNavigationSceneUtilityIsNotInvoked();
        }
    }

    private void removeSelfWhenNavigationSceneUtilityIsNotInvoked() {
        FractionScheduler fractionScheduler =getFractionAbility().getFractionManager().startFractionScheduler().remove(LifeCycleCompatFragment.this);
        FragmentUtility.commitFragment(fractionScheduler, false);
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (this.mSceneContainerLifecycleCallback != null) {
            this.mSceneContainerLifecycleCallback.onActive();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (this.mSceneContainerLifecycleCallback != null) {
            this.mSceneContainerLifecycleCallback.onInactive();
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        if (this.mSceneContainerLifecycleCallback != null) {
            this.mSceneContainerLifecycleCallback.onStop();
        }
    }

    @Override
    protected void onComponentDetach() {
        super.onComponentDetach();
        if (this.mSceneContainerLifecycleCallback != null) {
            this.mSceneContainerLifecycleCallback.onComponentDetach();
        }
    }
}